package EventLoopTest.Test004;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class ReactorPatternExample {
    public static void main(String[] args) throws InterruptedException {
        // 主 Reactor - 处理连接接受
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);

        // 从 Reactor - 处理 IO 读写
        int cpuCores = Runtime.getRuntime().availableProcessors();
        EventLoopGroup workerGroup = new NioEventLoopGroup(cpuCores);

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();

                            // 所有 Handler 都在同一个 EventLoop 中执行
                            pipeline.addLast("decoder", new StringDecoder());
                            pipeline.addLast("encoder", new StringEncoder());
                            pipeline.addLast("handler", new BusinessHandler());
                        }
                    });

            ChannelFuture future = bootstrap.bind(8888).sync();
            System.out.println("服务器启动");
            future.channel().closeFuture().sync();

        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static class BusinessHandler extends SimpleChannelInboundHandler<String> {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, String msg) {
            // 这个处理会在 Channel 绑定的 EventLoop 线程中执行
            EventLoop eventLoop = ctx.channel().eventLoop();
            System.out.println("处理线程: " + eventLoop);

            // 处理业务逻辑
            String response = processBusiness(msg);
            ctx.writeAndFlush(response);
        }

        private String processBusiness(String message) {
            // 模拟业务处理
            return "Processed: " + message.toUpperCase();
        }
    }
}